package stocks

import (
	"errors"
	"fmt"
	"html/template"
	"regexp"

	"gitee.com/chenrh/finego/app"
	"gitee.com/chenrh/finego/backends/models"
	"gitee.com/chenrh/finego/backends/ui"
	"gitee.com/chenrh/finego/backends/utils"
	"gitee.com/chenrh/gotoolkit/conv"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"gorm.io/gorm"
)

// StockWeighController 股票权衡
type StockWeighController struct {
	// Optionally: context is auto-binded by Iris on each request,
	// remember that on each incoming request iris creates a new UserController each time,
	// so all fields are request-scoped by-default, only dependency injection is able to set
	// custom fields like the Service which is the same for all requests (static binding).
	Ctx iris.Context

	// Our UserService, it's an interface which
	// is binded from the main application.
	//Service services.UserService
}

// BeforeActivation 注册自定义的路由
func (c *StockWeighController) BeforeActivation(b mvc.BeforeActivation) {
	// b.Handle("GET", "/weigh/home/index", "WeightIndex")
	b.Handle("GET", "/weigh/{stockcode:string}", "WeightStock")
	b.Handle("POST", "/weigh/savecomments", "SaveComments")
	b.Handle("POST", "/weigh/deletecomments", "DeleteComments")

}

// // WeightIndex 指数
// func (c *StockWeighController) WeightIndex() mvc.Result {

// 	stockCode := "index"
// 	var pageindex int64 = conv.ToInt64(c.Ctx.URLParam("page"), 1) - 1
// 	var pagesize int64 = 15
// 	var datacount int64 = 0
// 	datasql := fmt.Sprintf("select * from stock_comments a where a.company_code = '%s'", stockCode)
// 	cuntsql := fmt.Sprintf("select count(*) cnt from (%s) t", datasql)

// 	arr, _ := app.DB.Select(datasql+" order by a.created_at desc limit ?,?", pageindex*pagesize, pagesize)
// 	cnt, _ := app.DB.Select(cuntsql)

// 	if len(cnt) > 0 {
// 		datacount = cnt[0]["cnt"].(int64)
// 	}

// 	pagecontrol := ui.NewPagination(c.Ctx.Request(), datacount, pagesize)
// 	htmlpages := pagecontrol.Pages()

// 	return mvc.View{
// 		Name: "stocks/stocks.weigh.index.html",
// 		Data: iris.Map{
// 			"Title":        "指数推敲",
// 			"CommentsRows": arr,
// 			"PageControl":  template.HTML(htmlpages),
// 		},
// 	}
// }

// WeightStock  股票权衡界面
func (c *StockWeighController) WeightStock(stockCode string) mvc.Result {

	isindex := stockCode == "index"

	ismatch, _ := regexp.MatchString("^(0|3|6)[0-9]{5}$", stockCode)

	if isindex == false && ismatch == false {
		return mvc.Response{
			ContentType: "text/html",
			Text:        "<h4>此代码可能有误，未查到对应股票</h4>",
		}
		// return mvc.Response{Err: errors.New("此代码可能有误，未查到对应股票"), Code: 200}
	}

	var model models.STOCK_INFO
	if isindex {
		model.COMPANY_ABBR = "指数分析"
		model.COMPANY_CODE = "index"
	} else {
		result := app.GetDB().Where("company_code = ?", stockCode).First(&model)

		// 检查 ErrRecordNotFound 错误
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return mvc.Response{
				ContentType: "text/html",
				Text:        "<h1>此代码可能有误，未查到对应股票</h1>",
			}
			// return mvc.Response{Err: errors.New("此代码可能有误，未查到对应股票"), Code: 200}
		}
	}

	var pageindex int64 = conv.ToInt64(c.Ctx.URLParam("page"), 1) - 1
	var pagesize int64 = 15
	var datacount int64 = 0
	datasql := fmt.Sprintf("select * from stock_comments a where a.company_code = '%s'", stockCode)
	cuntsql := fmt.Sprintf("select count(*) cnt from (%s) t", datasql)

	arr, _ := app.DB.Select(datasql+" order by a.created_at desc limit ?,?", pageindex*pagesize, pagesize)
	cnt, _ := app.DB.Select(cuntsql)

	if len(cnt) > 0 {
		datacount = cnt[0]["cnt"].(int64)
	}

	pagecontrol := ui.NewPagination(c.Ctx.Request(), datacount, pagesize)
	htmlpages := pagecontrol.Pages()

	return mvc.View{
		Name: "stocks/stocks.weigh.html",
		Data: iris.Map{
			"Title":        "股票推敲：" + model.COMPANY_ABBR + "(" + stockCode + ")",
			"StockModel":   model,
			"CommentsRows": arr,
			"HasComments":  len(arr) > 0,
			"PageControl":  template.HTML(htmlpages),
		},
	}
}

// SaveComments 保存评论
func (c *StockWeighController) SaveComments() {

	content := c.Ctx.FormValue("content")
	code := c.Ctx.FormValue("code")

	haslogin, user := utils.UserCache(c.Ctx)

	if !haslogin {
		c.Ctx.JSON(iris.Map{"flag": false, "msg": "请选登录"})
		return
	}

	envmodel := models.STOCK_COMMENTS{
		USER_ID:      user.UserID,
		COMM_CONTENT: content,
		COMPANY_CODE: code,
	}
	envmodel.CreatedBy = user.NickName

	app.GetDB().Create(&envmodel)

	c.Ctx.JSON(iris.Map{"flag": true, "msg": "OK"})
	return
}

// DeleteComments 删除评论
func (c *StockWeighController) DeleteComments() {

	id := c.Ctx.FormValue("id")
	commID := conv.ToInt64(id, -1)

	haslogin, _ := utils.UserCache(c.Ctx)
	if !haslogin {
		c.Ctx.JSON(iris.Map{"flag": false, "msg": "请选登录"})
		return
	}

	mod := models.STOCK_COMMENTS{
		COMM_ID: commID,
	}

	app.GetDB().Delete(&mod)

	c.Ctx.JSON(iris.Map{"flag": true, "msg": "OK"})
	return
}
